package sword_offer;

import java.util.Arrays;

/**
 * @ClassName _29SpiralOrder
 * @Description: 顺时针打印矩阵
 * @Author: yongliang.ma
 * @Create_time:2022/10/9 14:14
 */
public class _29SpiralOrder {

    public static void main(String[] args) {
//        int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
        int[][] matrix = new int[][]{{7,8,9}};
        int[] ints = new _29SpiralOrder().spiralOrder(matrix);
        System.out.println(Arrays.toString(ints));
    }
    // 矩阵的款 高>=0
    public int[] spiralOrder(int[][] matrix){
        if (matrix == null || matrix.length == 0)
            return new int[]{};
        int rows = matrix.length, columns = matrix[0].length, start = 0;
        int[] result = new int[rows * columns];
        int size = 0;
        // 打印圈
        while (start * 2 < rows && start * 2 < columns){
            int endX = columns - start - 1, endY = rows - start - 1;
            // 水平 左 到 右
            for (int i = start; i <= endX; i++) {
                result[size++] = matrix[start][i];
            }
            // 竖直 上 到 下
            for (int i = start + 1; i <= endY; i++) {
                result[size++] = matrix[i][endX];
            }
            // 水平 右 到 左
            if (endY > start){
                for (int i = endX - 1; i >= start ; i--) {
                    result[size++] = matrix[endY][i];
                }
            }
            // 竖直 下 到 上
            if (endX > start){
                for (int i = endY - 1; i > start ; i--) {
                    result[size++] = matrix[i][start];
                }
            }
            start++;
        }

        return result;
    }
}
